package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.PmsBrandEntity;
import com.atguigu.gulimall.product.entity.PmsCategoryEntity;
import com.atguigu.gulimall.product.service.PmsBrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.PmsCategoryBrandRelationDao;
import com.atguigu.gulimall.product.entity.PmsCategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.PmsCategoryBrandRelationService;

import javax.annotation.Resource;


@Service("pmsCategoryBrandRelationService")
public class PmsCategoryBrandRelationServiceImpl extends ServiceImpl<PmsCategoryBrandRelationDao, PmsCategoryBrandRelationEntity> implements PmsCategoryBrandRelationService {

    @Resource
    private PmsCategoryServiceImpl categoryService;
    @Resource
    private PmsBrandService brandService;
    @Resource
    private PmsCategoryBrandRelationDao categoryBrandRelationDao;

    /**
     * 获取某个分类下所有品牌信息
     */
    @Override
    public List<PmsBrandEntity> getBrandsByCatId(Long catId) {
        List<PmsCategoryBrandRelationEntity> catelogId = categoryBrandRelationDao.selectList(new QueryWrapper<PmsCategoryBrandRelationEntity>().eq("catelog_id", catId));
        // 根据品牌id查询详细信息
        List<PmsBrandEntity> collect = catelogId.stream().map(item -> {
            Long brandId = item.getBrandId();
            PmsBrandEntity entity = brandService.getById(brandId);
            return entity;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PmsCategoryBrandRelationEntity> queryWrapper=new QueryWrapper<>();
        String brandId=(String) params.get("brandId");
        if(StringUtils.isNotBlank(brandId)) queryWrapper.eq("brand_id",brandId);
        IPage<PmsCategoryBrandRelationEntity> page = this.page(
                new Query<PmsCategoryBrandRelationEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void saveData(PmsCategoryBrandRelationEntity pmsCategoryBrandRelation) {
        Long catelogId=pmsCategoryBrandRelation.getCatelogId();
        PmsCategoryEntity categoryEntity = categoryService.getById(catelogId);
        pmsCategoryBrandRelation.setCatelogName(categoryEntity.getName());
        this.save(pmsCategoryBrandRelation);
    }

}